package com.alageek.crowd.mvc.config;

import com.alageek.crowd.entity.Admin;
import com.alageek.crowd.entity.Role;
import com.alageek.crowd.service.api.AdminService;
import com.alageek.crowd.service.api.AuthService;
import com.alageek.crowd.service.api.RoleService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CrowdUserDetailService implements UserDetailsService {

    private final AdminService adminService;
    private final RoleService roleService;
    private final AuthService authService;

    public CrowdUserDetailService(AdminService adminService, RoleService roleService, AuthService authService) {
        this.adminService = adminService;
        this.roleService = roleService;
        this.authService = authService;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Admin admin = adminService.getAdmin(new Admin(s, null)).get(0);
        List<Role> assignedRoleList = roleService.getAssignedRole(admin.getId());
        List<String> authNameList = authService.getAssignedAuthNameByAdminId(admin.getId());
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role role : assignedRoleList) {
            String roleName = "ROLE_" + role.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }
        for (String auth : authNameList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(auth);
            authorities.add(simpleGrantedAuthority);
        }
        return new SecurityAdmin(admin, authorities);
    }

}
